<script setup>
import {ref, computed} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import axios from '@/api/server';

const router = useRouter();

const dialogVisible = ref(false);
const questions = ref([]);
const currentQuestionIndex = ref(0);
const selectedAnswer = ref('');
const showCorrectAnswer = ref(false);
const activeMenu = ref('1'); // 新增菜单激活状态

// 加载错题列表
const loadWrongQuestions = async () => {
  try {
    const res = await axios.get('/question/listWrong');
    console.log('API响应:', res);

    // 检查响应结构
    if (!res.data || res.data.code !== 1) {
      throw new Error(res.data?.msg || '获取错题失败，服务器返回异常');
    }

    const data = res.data.data;
    console.log('错题数据:', data);

    if (!data || data.length === 0) {
      ElMessage.info('您当前没有错题');
      questions.value = [];
      return;
    }

    // 处理数据格式
    questions.value = data.map(q => {
      // 确保选择题选项处理
      const processedOptions = q.questionType === 'choice' && q.questionChoicesList
          ? processOptions(q.questionChoicesList)
          : q.questionChoicesList || [];

      // 确保用户答案存在
      const userAnswer = q.userAnswer || '';

      // 确保正确答案存在
      const correctAnswer = q.correctAnswer || '';

      // 确保问题内容存在
      const content = q.content || '题目内容缺失';

      return {
        ...q,
        content,
        userAnswer,
        correctAnswer,
        questionChoicesList: processedOptions
      };
    });

    // 设置当前题目
    if (questions.value.length > 0) {
      currentQuestionIndex.value = 0;
      selectedAnswer.value = questions.value[0].userAnswer || '';
      showCorrectAnswer.value = true;
    }
  } catch (err) {
    console.error('加载错题失败:', err);

    // 更详细的错误处理
    if (err.response) {
      // HTTP 状态码错误
      if (err.response.status === 500) {
        ElMessage.error('服务器内部错误，请稍后再试');
      } else {
        ElMessage.error(`请求失败: ${err.response.status} ${err.response.statusText}`);
      }

      // 显示后端返回的错误信息
      if (err.response.data && err.response.data.msg) {
        ElMessage.error(`错误详情: ${err.response.data.msg}`);
      }
    } else if (err.request) {
      // 请求未发出
      ElMessage.error('网络请求失败，请检查网络连接');
    } else {
      // 其他错误
      ElMessage.error(`加载错题失败: ${err.message}`);
    }

    // 清空问题列表
    questions.value = [];
  }
};

// 处理选项：去重 + 去掉前缀
const processOptions = (options) => {
  const seen = new Set();
  return options
      .filter(option => {
        // 提取纯文本内容（去掉A. B.等前缀）
        const cleanText = option.choiceContent.replace(/^[A-Za-z]\.\s*/, '');
        if (!seen.has(cleanText)) {
          seen.add(cleanText);
          return true;
        }
        return false;
      })
      .slice(0, 4) // 确保最多4个选项
      .map((option, index) => ({
        ...option,
        // 重新生成标准化的选项标签 (A. B. C. D.)
        choiceContent: `${String.fromCharCode(65 + index)}. ${option.choiceContent.replace(/^[A-Za-z]\.\s*/, '')}`
      }));
};

// 获取选项标签（A/B/C/D）
const getOptionLabel = (content) => {
  const match = content.match(/^([A-D])\./);
  return match ? match[1] : content;
};

// 获取选项纯文本内容（去掉A. B.等前缀）
const getOptionText = (content) => {
  return content.replace(/^[A-Za-z]\.\s*/, '');
};

loadWrongQuestions();

// 当前题目
const currentQuestion = computed(() => {
  return questions.value[currentQuestionIndex.value] || null;
});

// 上一题/下一题逻辑保持不变
const prevQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--;
    selectedAnswer.value = currentQuestion.value.userAnswer || '';
    showCorrectAnswer.value = true;
  } else {
    ElMessage.info('已经是第一题了');
  }
};

const nextQuestion = () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++;
    selectedAnswer.value = currentQuestion.value.userAnswer || '';
    showCorrectAnswer.value = true;
  } else {
    ElMessage.info('已经是最后一题了');
  }
};

// 导航相关方法
const handleSelect = (index) => console.log('当前菜单项：', index);
const goBackHome = () => router.push('/home');
const goToPersonal = () => router.push('/personal');
const goToCollection = () => router.push('/collection');
const goToAdmin = () => router.push('/admin/manage');

const logout = async () => {
  try {
    await axios.post('/users/logout'); // 会自动带上 Bearer token
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    ElMessage.success('退出成功');
    await router.push('/');
  } catch (error) {
    console.error('退出失败：', error);
    ElMessage.error('退出失败');
  }
};
</script>

<template>
  <div class="wrong-page">
    <!-- 修改后的导航栏 -->
    <el-header class="navbar">
      <div class="logo" @click="goBackHome" style="cursor:pointer;">思不罔学习平台</div>
      <el-menu mode="horizontal" :default-active="activeMenu" @select="handleSelect">
        <el-menu-item index="1" @click="goBackHome">首页</el-menu-item>
        <el-menu-item index="2" @click="goToPersonal">个人中心</el-menu-item>
        <el-menu-item index="3" @click="goToCollection">我的收藏</el-menu-item>
      </el-menu>
      <div class="auth-buttons">
        <el-button type="text" @click="goToAdmin">管理员入口</el-button>
        <el-button type="text" @click="logout">退出登录</el-button>
      </div>
    </el-header>

    <h2 class="section-title">我的错题册</h2>

    <div v-if="questions.length === 0" class="no-questions">
      当前没有错题哦，去练习提升吧！
    </div>

    <div v-else class="wrong-question-card">
      <div class="question-header">
        <div>题目 {{ currentQuestionIndex + 1 }} / {{ questions.length }}</div>
      </div>

      <div class="question-content" v-html="currentQuestion?.content"></div>

      <!-- 选择题选项展示 -->
      <div class="options-container" v-if="currentQuestion?.questionType === 'choice'">
        <div class="option-item"
             v-for="(option, index) in currentQuestion.questionChoicesList"
             :key="option.choiceId">
          <span class="option-label">{{ getOptionLabel(option.choiceContent) }}.</span>
          <span :class="{'correct-option': option.isCorrect}">
            {{ getOptionText(option.choiceContent) }}
          </span>
        </div>
        <div class="correct-answer">
          <strong>正确答案：</strong>
          <span class="correct-text">{{ currentQuestion.answer }}</span>
        </div>
      </div>

      <!-- 填空题答案展示 -->
      <div class="fill-answer" v-if="currentQuestion?.questionType === 'fill_in'">
        <div class="correct-answer">
          <strong>正确答案：</strong>
          <span class="correct-text">{{ currentQuestion.answer }}</span>
        </div>
      </div>

      <div class="pagination-buttons">
        <el-button @click="prevQuestion" type="primary" plain>上一题</el-button>
        <el-button @click="nextQuestion" type="primary" plain>下一题</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import "../styles/Wrong.css";

/* 新增导航栏样式 */
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 60px;
}

.logo {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
}

.auth-buttons {
  margin-left: auto;
}

.el-menu {
  border-bottom: none;
}

.el-menu-item {
  font-size: 16px;
}
</style>